/**
 * @file BluetoothTransparentModule.cpp
 * @author your name (you@domain.com)
 * @brief 蓝牙透传模块
 * @version 0.1
 * @date 2023-06-27
 * 
 * @copyright Copyright (c) 2005-2023 XAG Co., Ltd. All Rights Reserved
 * 
 */

#pragma once

#include <cinttypes>
#include <cstdint>
#include <string>
#include <memory>
#include <vector>
#include <set>

#include "BluetoothTransparentModule.h"
#include "XnetCommModule_Impl.h"

namespace kapok_hardware {
class XAG_SerialPort;
}

/* at instruction execute okay */
#define AT_INSTRUCTION_OK       "OK"

/* at instruction execute error */
#define AT_INSTRUCTION_ERROR    "ERROR"

/* function return fail */
#define FAIL        0xFF

/* function return ok */
#define OKAY        0


/* bluetooth buffer length */
#define BT_BUFFER_LEN       256

/* command length */
#define BT_INSTRUCTION_LEN  64



/* bluetooth AT instruction */

/* 进入AT配置 */
#define BT_ENTER_AT     "AT...\r\n"

/* 复位芯片 */
#define BT_RESET        "AT+RESET\r\n"

/* 获取芯片版本号 */
#define BT_VER      "AT+VER\r\n"

/* 串口设置指令:AT+UART=<波特率>,<数据位>,<停止位>,<校验位>,<超时时间>{CR}{LF} */
#define BT_SET_UART "AT+UART=%d,%d,%d,%d,%d\r\n"

/* 设备信息的系统ID */
#define BT_SYSID        "AT+SYSID?\r\n"

/* 设备信息的序列号 */
#define BT_GET_SERINUM  "AT+SERINUM?\r\n"
#define BT_SET_SERINUM  "AT+SERINUM=%s\r\n"

/* 获取蓝牙工作模式 */
#define BT_GET_BLEMODE  "AT+BLEMODE?\r\n"

/*
 * 设置模式的参数x为：0(广播模式) 、1(主机模式) 、2(设备模式)
 * 命令接收后保存该配置参数，在下一次重启才执行
 */
#define BT_SET_BLEMODE  "AT+BLEMODE=%d\r\n"
#define MODE_BROADCAST  0
#define MODE_MASTER     1
#define MODE_DEVICE     2

/* 广播使能控制 */
#define BT_GET_ADVEN    "AT+ADVEN?\r\n"
#define BT_SET_ADVEN    "AT+ADVEN=%s\r\n"   /* ON or OFF */

/* 广播数据 */
#define BT_GET_ADVDAT   "At+ADVDAT?\r\n"
#define BT_SET_ADVDAT   "AT+ADVDAT=%s\r\n"

/* 广播通道设置 */
#define BT_GET_BCCH         "AT+BCCH?\r\n"
#define BT_SET_BCCH         "AT+BCCH=%d\r\n"

/* 广播间隔设置 */
#define BT_GET_ADVINTER     "AT+ADVINTER?\r\n"
#define BT_SET_ADVINTER     "AT+ADVINTER=%d\r\n"


namespace business_modules_bluetoothtransparent {

class BluetoothTransparentModule_Impl : public BluetoothTransparentModule {
 public:
    BluetoothTransparentModule_Impl();
    virtual ~BluetoothTransparentModule_Impl();

    bool Init(void) override;
    bool Uninit(void) override;

    bool SetXnetCommModule(std::shared_ptr<business_modules_xnetcomm::XnetCommModule> spXnetComm) override;
    bool BluetoothFactoryTest(void);

 private:
    int32_t SendThread(void);
    int32_t RegRecvCb(void);
    int32_t UnRegRecvCb(void);

 private:
    std::shared_ptr<business_modules_xnetcomm::XnetCommModule> m_spXnetComm = nullptr;
    bool m_bRunning = false;
    std::thread m_thId;
};

} /* namespace business_modules_bluetoothtransparent */
